import UserSession from "@/UserSession";
import { accountUpdateNick, accountUpdatePassword } from "@/services/geographic";
import jsonDataUtils from "@/utils/jsonDataUtils";
import { Button, Form, Input, Modal, Tabs, Upload, message } from "antd";
import React from "react";

class MyAccount extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      activeKey:"account",
      picture:""
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = () => {
    this.setState({
      visible:true
    },() => {
      let currentUser = UserSession.getCurrentUser()
      this.props.form.setFieldsValue({
        name:currentUser.username,
        nick:currentUser.nick,
        mobilePhone:currentUser.mobilePhone
      })
      this.setState({picture:currentUser.picture})
    })
  }

  onChange = activeKey => {
    this.setState({activeKey})
  }

  onCancel = () => {
    this.setState({visible:false,activeKey:"account",
    picture:""})
  }

  checkName=(rule, value, callback)=>{
    if(value.length>20){
      callback('昵称限制20个字符')
    }else{
      callback()
    }
  };

  checkMobilePhone=(rule, value, callback)=>{
    const reg = /^1[3456789]\d{9}$/;
    if (value) {
      if (reg.test(value)) {
        callback();
      } else {
        callback('请输入正确的手机号');
      }
    } else {
      callback('请输入手机号');
    }
  };

  beforeUpload = file => {
    let b = /\.(png|jpg|gif)$/;
    let a = file.name.toLowerCase();

    const pig = b.test(a);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!pig) {
      if (!isLt2M) {
        message.error('请上传小于2M的图片');
      } else {
        message.error('请上传图片格式');
      }
    } else {
      if (!isLt2M) {
        message.error('请上传小于2M的图片');
      }
    }
    return isJPG && isLt2M && pig;
  };

  handleChangeImage = (info, type) => {
    if (info.file.status === 'done') {
      this.setState({
        picture: info.file.response.url,
      });
    }
  };

  doOk = () => {
    const { activeKey } = this.state;
    let fields = activeKey == 'account' ? ['name','nick','mobilePhone'] : ['password','newPassword','repeatPassword']
    this.props.form.validateFields(fields,(errors,values) => {
      if(!errors){
        if(activeKey == 'account'){
          this.doSaveAccount(values)
        }else{
          this.doUpdatePassword(values)
        }
      }
    })
  }

  doSaveAccount = async values => {
    const { picture } = this.state;
    const res = await accountUpdateNick({nick:values.nick,mobilePhone:values.mobilePhone,picture})
    if(res.code == -1){}else{
      setTimeout(()=>{
        location.reload()
      },100)
    }
    
  }

  doUpdatePassword = async values => {
    console.log(values);
    const res = await accountUpdatePassword(values)
    if(res.code == -1){}else{
      message.info(res.message)
      this.onCancel()
    }
  }

  checkFieldForPassword(rule, value, callback) {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
    if (value) {
      if (reg.test(value)) {
        if (value.length > 30 || value.length < 6) {
          callback('只可填入8-20位数字和字母组合');
        } else {
          callback();
        }
      } else {
        callback('只可填入8-20位数字和字母组合');
      }
    } else {
      callback('只可填入8-20位数字和字母组合');
    }
  }

  render(){
    const { visible,activeKey ,picture} = this.state;
    const { form:{getFieldDecorator} } = this.props;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
    };
    return(
      <Modal visible={visible} onCancel={this.onCancel} width={600} okText={activeKey == 'account' ? '保存信息' : '修改密码'} onOk={this.doOk}>
        <Form {...formItemLayout}>
          <Tabs activeKey={activeKey} onChange={this.onChange}>
            <Tabs.TabPane tab="账户信息" key="account">
              <Form.Item label="用户名">
                {getFieldDecorator("name")(
                  <Input disabled />
                )}
              </Form.Item>
              <Form.Item label="用户昵称">
                {getFieldDecorator("nick", {rules: [{required: true, message: '昵称不能为空'},{validator:this.checkName}]})(
                  <Input />
                )}
              </Form.Item>
              <Form.Item label="手机号">
                {getFieldDecorator("mobilePhone", {rules: [{required: true, message: '手机号不能为空'},{validator:this.checkMobilePhone}]})(
                  <Input />
                )}
              </Form.Item>
              <Form.Item label="用户头像">
                {getFieldDecorator("url")(
                  <Upload
                    name="file"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/cloud/file/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeImage}
                    accept=".png,.jpg"
                  >
                  {
                    picture && picture != '1' ? (
                      <img src={picture} alt="file" style={{marginRight:10,width:72,height:72}} />
                    ) : <img src='/robotConfigImg/user.png' alt="file" style={{marginRight:10,width:72,height:72}} />
                  }
                    
                    <Button size={'small'}>
                      选择文件
                    </Button>
                  </Upload>
                )}
              </Form.Item>
            </Tabs.TabPane>
            <Tabs.TabPane tab="修改密码" key="password">
              <Form.Item label="当前密码">
                {getFieldDecorator("password",{rules:[{required:true,message:"当前密码不能为空"}]})(
                  <Input.Password />
                )}
              </Form.Item>
              <Form.Item label="新的密码">
                {getFieldDecorator("newPassword",{rules:[{required:true,message:"新密码不能为空"},{validator: this.checkFieldForPassword}]})(
                  <Input.Password />
                )}
              </Form.Item>
              <Form.Item label="重复新密码">
                {getFieldDecorator("repeatPassword",{rules:[{required:true,message:"重复新密码不能为空"}]})(
                  <Input.Password />
                )}
              </Form.Item>
            </Tabs.TabPane>
          </Tabs>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(MyAccount)